package com.lxd.milktea.interceptor;

import com.lxd.milktea.constant.CookieConstant;
import com.lxd.milktea.constant.RedisConstant;
import com.lxd.milktea.enums.ResultEnum;
import com.lxd.milktea.service.UserService;
import com.lxd.milktea.util.CookieUtil;
import com.lxd.milktea.util.ResultVOUtil;
import com.lxd.milktea.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author carrymaniac
 * @date Created in 13:24 2019-08-10
 * @description
 **/
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie==null||cookie.getValue()==null){
            WebUtil.sendJsonMessage(response, ResultVOUtil.fail(Integer.valueOf(ResultEnum.USER_NO_LOGIN.getCode()),ResultEnum.USER_NO_LOGIN.getMsg()));
            return false;
        }
        String tokenValue = stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if(StringUtils.isEmpty(tokenValue)){
            WebUtil.sendJsonMessage(response, ResultVOUtil.fail(Integer.valueOf(ResultEnum.USER_NO_LOGIN.getCode()),ResultEnum.USER_NO_LOGIN.getMsg()));
            return false;
        }
        return true;
    }

    /**
     * 往每一个视图层中添加user数据，以便使用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
